package com.example.sqliteviewer;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.File;

public class CreateDatabaseActivity extends AppCompatActivity {

    private EditText etDatabaseName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_database);
        
        setTitle("新建数据库");
        
        etDatabaseName = findViewById(R.id.etDatabaseName);
        Button btnCreate = findViewById(R.id.btnCreate);
        Button btnCancel = findViewById(R.id.btnCancel);
        
        btnCreate.setOnClickListener(v -> createDatabase());
        btnCancel.setOnClickListener(v -> finish());
    }
    
    private void createDatabase() {
        String databaseName = etDatabaseName.getText().toString().trim();
        
        if (databaseName.isEmpty()) {
            Toast.makeText(this, "请输入数据库名称", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 确保文件名有正确的扩展名
        if (!databaseName.endsWith(".db") && !databaseName.endsWith(".sqlite") && !databaseName.endsWith(".sqlite3")) {
            databaseName += ".db";
        }
        
        // 创建数据库文件的目录
        File tempDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "Misc");
        if (!tempDir.exists())   tempDir.mkdirs();

        
        // 创建数据库文件路径
        File databaseFile = new File(tempDir, databaseName);

        try {
            // 创建空的SQLite数据库
            SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databaseFile, null);
            database.close();
            
            // 将数据库路径添加到历史记录
            DatabaseHistoryManager historyManager = new DatabaseHistoryManager(this);
            historyManager.addToHistory(databaseFile.getAbsolutePath());
            
            Toast.makeText(this, "数据库创建成功", Toast.LENGTH_SHORT).show();
            
            // 打开新创建的数据库
            Intent intent = new Intent(this, DatabaseViewerActivity.class);
            intent.putExtra("DATABASE_PATH", databaseFile.getAbsolutePath());
            startActivity(intent);
            
            // 关闭当前Activity
            finish();
            
        } catch (Exception e) {
            Toast.makeText(this, "创建数据库失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
}